// 顶点着色器
var VSHADER_SOURCE =
    'attribute vec4 a_Position;\n' +
    'uniform vec4 u_Translation;\n' +
    'void main() {\n' +
    '   gl_Position = a_Position + u_Translation;\n' +
    //  '   gl_PointSize = 20.0;\n' +
    '}\n';

// 片元着色器
var FSHADER_SOURCE =
    'precision mediump float;\n' + // 精确限定词
    'uniform vec4 u_FragColor;\n' +
    'void main() {\n' +
    ' gl_FragColor = u_FragColor;\n' +
    '}\n';

// 在  x y z 方向上平移的距离
var Tx = 0.5,
    Ty = 0.5,
    Tz = 0.0;

function main() {
    // 获取 canvas 元素
    var canvas = document.getElementById('webgl');
    // 获取 WebGL 上下文
    var gl = getWebGLContext(canvas);
    if(!gl) {
        console.log('Failed to get the rendering content of WebGL');
        return;
    }
    // 初始化着色器
    if(!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('Failed to initialize shaders.');
        return;
    }
    // 设置顶点位置
    var n = initVertexBuffers(gl);
    if(n < 0) {
        console.log('');
        return;
    }

    var u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
    if(!u_FragColor) {
        console.log('Failed to get u_FragColor variable');
        return;
    }
    gl.uniform4f(u_FragColor, 0.6, 0.1, 0.2, 1.0);

    var u_Translation = gl.getUniformLocation(gl.program, 'u_Translation');
    if(!u_Translation) {
        console.log('Failed to get u_Translation variable.');
        return;
    }
    gl.uniform4f(u_Translation, Tx, Ty, Tz, 0.0);
    
    // 设置背题色
    gl.clearColor(0.0, 0.0, 0.0, 1.0);

    // 清空 <canvas>
    gl.clear(gl.COLOR_BUFFER_BIT);

    // 绘制三个点
    gl.drawArrays(gl.TRIANGLES, 0, n);
}

// 初始化缓冲区
function initVertexBuffers(gl) {
    var vertices = new Float32Array([
        0.0, 0.5, -0.5, -0.5,
        0.5, -0.5
    ]);

    var n = 3;

    // 创建缓冲区对象
    var vertexBuffer = gl.createBuffer();
    if(!vertexBuffer) {
        console.log('Failed to create the buffer object!');
        return -1;
    }

    // 将缓冲区对象绑定到目标
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    // 向缓冲区对象中写入数据
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

    var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    if(a_Position < 0) {
        console.log('Failed to get the storage location of a_Position');
        return;
    }

    // 将缓存区对象分配给变量
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
    // 开启 attribute 变量
    gl.enableVertexAttribArray(a_Position);
    return n;
}